package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"order/api/request"
	"order/inter/dao"
	"order/inter/model"
)

func CreateOrder(c *gin.Context) {
	var req request.CreateOrder
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var order model.Orderes
	dao.GetOneByFields(&model.Orderes{
		Status: uint8(req.Status),
	}, &order)
	if order.Id != 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "此账号不存在",
			"data": nil,
		})
		return
	}
	order = model.Orderes{
		OrderId:   uint32(req.OrderId),
		ProductId: uint32(req.ProductId),
		Status:    uint8(req.Status),
	}
	if !dao.Create(&order) {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "订单添加失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "ok",
		"data": order,
	})
}

// 查询全部订单
func FindOrder(c *gin.Context) {
	var pro []model.Orderes
	dao.GetListByFields(&model.Orderes{}, &pro)

	var pros []*model.Orderes
	for _, v := range pro {
		pros = append(pros, &v)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "ok",
		"data": pros,
	})
}

// 修改订单数据
func UpdateOrder(c *gin.Context) {
	var req request.UpdateOrder
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": dao.Update(&model.Orderes{
			Id:        uint64(req.Id),
			OrderId:   uint32(req.OrderId),
			ProductId: uint32(req.ProductId),
			Status:    uint8(req.Status),
		}),
	})
}

// 删除订单数据
func DelOrder(c *gin.Context) {
	var req request.DelOrder
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "OK",
		"data": dao.Delete(&model.Orderes{
			Id: uint64(req.Id),
		}),
	})
}
